package ParcelDelivery;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Properties;
import java.util.Scanner;

import org.apache.log4j.Logger;
import org.omg.CORBA.ORB;
import org.omg.CosNaming.NameComponent;
import org.omg.CosNaming.NamingContext;
import org.omg.CosNaming.NamingContextHelper;

import be.fundp.info.util.logging.MyLogger;

import BookStore.managers.DeliveryBookStoreMgr_Iface.DeliveryBookStoreMgr;
import BookStore.managers.DeliveryBookStoreMgr_Iface.DeliveryBookStoreMgrHelper;
import Util.CSVBookParser;
import Util.Util;

public class DeliveryMainInterface {

	private static final String prop = "Delivery.properties";
	private static String ip;
	private static String port;
	private static String BS;
	private static String file;
	private static ORB orb;
	public static Logger logger;
	private static CSVBookParser parser;
	private static final String log4j = "log4j.properties";

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {

		if (!MyLogger.isConfigured())
			MyLogger.initLogger(log4j);
		logger = MyLogger.getLogger(Class.class);

		ip = Util.getPropertiesAttribute(prop, "ip");
		port = Util.getPropertiesAttribute(prop, "port");
		BS = Util.getPropertiesAttribute(prop, "BS");
		file = Util.getPropertiesAttribute(prop, "csv");
		if (ip == null || port == null || file == null) {
			System.out.println("[ERROR] File " + prop + " is absent.");
			return;
		}
		parser = new CSVBookParser();

		while (1 == 1) {

			System.out.println("Press Enter to show the list of delivery ");
			BufferedReader input=new BufferedReader(new InputStreamReader(System.in)); 
			input.readLine();
			System.out.println("Reading the file :  " + file);
			BufferedReader reader = parser.open(file, Charset.defaultCharset());
			if (reader == null) {
				System.out.println("The file " + file + " is absent...");
				return;
			}
			String line;
			int i = -1;
			try {

				while (reader.ready()) {
					i++;
					line = reader.readLine();
					System.out.println("(" + i + ") " + line);

				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (i == -1) {
				System.out.println("There is currently no delivery...");
				return;
			}

			System.out
					.println("\nEnter the line number of the delivery to return [0-"
							+ i + "]: ");

			int rline = -1;
			String str = null;
			boolean found = false;
			while (!found) {
				try {
					rline = Integer.parseInt(input.readLine());
					if (rline >= 0 && rline <= i)
						found = true;
					else throw new Exception();
				} catch (Exception e) {
					System.out.println("Wrong input. Re-try:");
				}
			}

			reader = parser.open(file, Charset.defaultCharset());
			i = 0;
			while (i < rline + 1) {
				try {
					str = reader.readLine();
					i++;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			logger.info("Line = " + str);
			String[] splt = str.split(";");
			String isbn, idBS, lastname, firstname;
			isbn = splt[0];
			idBS = splt[1];
			lastname = splt[2];
			firstname = splt[3];
			DeliveryBookStoreMgr bs = getBSMgr(idBS);
			if (bs == null) {
				System.out
						.println("Sorry but the bookstore " + idBS + " is currently unavailable...");
				return;
			}
			bs.returnBook(isbn, lastname, firstname);
			logger.info("The book has been returned and notified to the bookstore");

		}
	}

	private static DeliveryBookStoreMgr getBSMgr(String idBS) {

		Properties props = new Properties();
		props.put("org.omg.CORBA.ORBInitialHost", ip);
		props.put("org.omg.CORBA.ORBInitialPort", port);

		// initialize ORB
		orb = ORB.init(new String[] { "-ORBInitialPort", port,
				"-ORBInitiaHost", ip }, props);

		// retrieve Naming service
		org.omg.CORBA.Object objNameService = orb
				.string_to_object("corbaloc:iiop:" + ip + ":" + port
						+ "/NameService");
		NamingContext context = NamingContextHelper.narrow(objNameService);

		NameComponent[] name = new NameComponent[] { new NameComponent(
				"Delivery", "Object" + idBS) };
		try {
			return DeliveryBookStoreMgrHelper.narrow(context.resolve(name));
		} catch (Exception e) {
			return null;
		}

	}

}
